<template>
  <div class="user-wishlist">
    <el-card class="wishlist-card">
      <template #header>
        <div class="card-header">
          <span>我的收藏</span>
          <el-button v-if="selectedItems.length > 0" type="danger" @click="batchRemove">
            批量删除 ({{ selectedItems.length }})
          </el-button>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <div v-else-if="wishlist.length === 0" class="empty-container">
        <el-empty description="暂无收藏商品">
          <el-button type="primary" @click="goToHome">去购物</el-button>
        </el-empty>
      </div>

      <div v-else class="wishlist-content">
        <el-table :data="wishlist" @selection-change="handleSelectionChange" class="wishlist-table">
          <el-table-column type="selection" width="55" />

          <el-table-column label="商品信息" min-width="400">
            <template #default="{ row }">
              <div class="product-info">
                <el-image
                  :src="row.productImageUrl || '/placeholder-product.jpg'"
                  :alt="row.name"
                  class="product-image"
                  fit="cover"
                />
                <div class="product-details">
                  <h4 class="product-name" @click="goToProduct(row.shoeId)">
                    {{ row.name }}
                  </h4>
                  <p class="product-brand">{{ row.brand?.brand_name || '未知品牌' }}</p>
                  <p class="product-type">{{ row.type?.typeName || '未知类型' }}</p>
                  <p class="product-price">¥{{ getCurrentPrice(row) }}</p>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="上市时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.launchDate) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button size="small" type="danger" @click="handleRemoveFromWishlist(row.shoeId)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div v-if="totalPages > 1" class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            :page-sizes="[12, 24, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { getWishlistPage, removeFromWishlist } from '@/api/wishlistService'
import type { WishlistItemWithShoes } from '@/types/wishlist'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const wishlist = ref<WishlistItemWithShoes[]>([])
const selectedItems = ref<WishlistItemWithShoes[]>([])
const currentPage = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
const user = computed(() => authStore.user)

// 方法
const fetchWishlist = async () => {
  if (!user.value?.id) {
    ElMessage.error('请先登录')
    return
  }

  loading.value = true
  try {
    const response = await getWishlistPage(user.value.id, currentPage.value, pageSize.value)
    if (response.data.code === 200) {
      console.log('收藏列表数据:', response.data.data)
      console.log('收藏列表第一项:', response.data.data.list[0])
      console.log('收藏列表第一项的所有字段:', Object.keys(response.data.data.list[0] || {}))
      wishlist.value = response.data.data.list
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.msg || '获取收藏列表失败')
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
  } finally {
    loading.value = false
  }
}

const handleSelectionChange = (selection: WishlistItemWithShoes[]) => {
  selectedItems.value = selection
}

const getCurrentPrice = (item: WishlistItemWithShoes) => {
  return (item.discountPrice || item.price)?.toFixed(2)
}

// 已移除加入购物车功能

const handleRemoveFromWishlist = async (shoeId: number) => {
  console.log('删除收藏，shoeId:', shoeId)
  try {
    await ElMessageBox.confirm('确认从收藏中删除该商品？', '删除收藏', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })

    if (!user.value?.id) {
      ElMessage.error('用户信息不存在')
      return
    }

    const response = await removeFromWishlist(shoeId, user.value.id)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchWishlist()
    } else {
      ElMessage.error(response.data.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const batchRemove = async () => {
  if (selectedItems.value.length === 0) return

  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedItems.value.length} 个收藏商品？`,
      '批量删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    // 实现批量删除功能
    if (!user.value?.id) {
      ElMessage.error('用户信息不存在')
      return
    }

    loading.value = true
    let successCount = 0
    let failCount = 0

    // 遍历选中的商品，逐个调用删除API
    for (const item of selectedItems.value) {
      try {
        const response = await removeFromWishlist(item.shoeId, user.value.id)
        if (response.data.code === 200) {
          successCount++
        } else {
          failCount++
          console.error(`删除商品 ${item.name} 失败:`, response.data.msg)
        }
      } catch (error) {
        failCount++
        console.error(`删除商品 ${item.name} 时发生错误:`, error)
      }
    }

    // 显示删除结果
    if (failCount === 0) {
      ElMessage.success(`批量删除成功，共删除 ${successCount} 个商品`)
    } else if (successCount > 0) {
      ElMessage.warning(`部分删除成功：成功 ${successCount} 个，失败 ${failCount} 个`)
    } else {
      ElMessage.error('批量删除失败')
    }

    // 清空选中项并刷新列表
    selectedItems.value = []
    fetchWishlist()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchWishlist()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchWishlist()
}

const formatDate = (date: string) => {
  if (!date) return '未知'
  
  try {
    return new Date(date).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
  } catch (error) {
    console.error('日期格式化失败:', error, date)
    return '日期错误'
  }
}

const goToProduct = (shoeId: number) => {
  router.push(`/product/${shoeId}`)
}

const goToHome = () => {
  router.push('/')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchWishlist()
})
</script>

<style scoped>
.user-wishlist {
  width: 100%;
}

.wishlist-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 40px 0;
}

.empty-container {
  padding: 60px 0;
}

.wishlist-content {
  margin-bottom: 20px;
}

.wishlist-table {
  margin-bottom: 20px;
}

.product-info {
  display: flex;
  gap: 16px;
  align-items: center;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0 0 8px 0;
  cursor: pointer;
  transition: color 0.2s;
}

.product-name:hover {
  color: #409eff;
}

.product-brand {
  font-size: 14px;
  color: #606266;
  margin: 0 0 4px 0;
}

.product-type {
  font-size: 12px;
  color: #909399;
  margin: 0 0 8px 0;
}

.product-price {
  font-size: 16px;
  font-weight: 600;
  color: #e6a23c;
  margin: 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

@media (max-width: 768px) {
  .product-info {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .product-image {
    width: 100%;
    height: 200px;
  }
}
</style>
